package ganga.custodian.security;

import ganga.custodian.CustodianApplication;
import ganga.custodian.R;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class IdentificationActivity extends Activity {
	Properties props;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.identivicationactivity);
		setCurrentTheme();
		setListMenu();

	}

	/**
	 * Загружает список имен из файла
	 */
	public void setListMenu() {
		ArrayList<String> inputArrayOfName = new ArrayList<String>();
		Properties props = new Properties();
		loadHumanList(props);
		Enumeration<?> nameEnum = props.propertyNames();
		while (nameEnum.hasMoreElements()) {
			inputArrayOfName.add(nameEnum.nextElement().toString());
		}

		ArrayAdapter<String> inputAdapter = new ArrayAdapter<String>(this,	android.R.layout.simple_spinner_item, inputArrayOfName);
		inputAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Spinner selectUserSpinner = (Spinner) findViewById(R.id.identificationSpinner);
		selectUserSpinner.setAdapter(inputAdapter);
	}

	@Override
	protected void onResume() {
		super.onResume();
		setCurrentTheme();
	}

	/**
	 * Задает текущую тему
	 */
	public void setCurrentTheme() {
		LinearLayout thisLayout = (LinearLayout) findViewById(R.id.identivicationLayout);
		thisLayout.setBackgroundColor(CustodianApplication.getInstance().selectTheme.backGround);
		TextView label1 = (TextView) findViewById(R.id.identificationLabel1);
		label1.setTextColor(CustodianApplication.getInstance().selectTheme.firstColour);
		TextView label2 = (TextView) findViewById(R.id.identificationLabel2);
		label2.setTextColor(CustodianApplication.getInstance().selectTheme.firstColour);
		TextView label3 = (TextView) findViewById(R.id.identificationLabel3);
		label3.setTextColor(CustodianApplication.getInstance().selectTheme.firstColour);
		TextView label4 = (TextView) findViewById(R.id.identificationLabel4);
		label4.setTextColor(CustodianApplication.getInstance().selectTheme.firstColour);
		CheckBox checkbox = (CheckBox) findViewById(R.id.identificationCheckBox);
		checkbox.setTextColor(CustodianApplication.getInstance().selectTheme.secondColour);
	}

	public void getUserInfo_Click(View v) {
		Spinner spin =(Spinner)findViewById(R.id.identificationSpinner);
		if(spin.getAdapter().getCount()!=0)
		userAutorization();
		else
			Toast.makeText(this, "Список позьователей пуст", Toast.LENGTH_SHORT).show();
	}

	/**
	 * Функция проверяет введенные пароль и логин с соответсвующими им
	 * в XML файле, если они совпадают, то оповещение, что удачное переключение
	 */
	public void userAutorization() {
		CheckBox checkBox = (CheckBox) findViewById(R.id.identificationCheckBox);
		EditText editText = (EditText) findViewById(R.id.identificationEditText);
		Spinner spinner = (Spinner) findViewById(R.id.identificationSpinner);
		@SuppressWarnings("unused")
		boolean LockUserInfo = checkBox.isChecked();
		String User = spinner.getSelectedItem().toString();
		String Password = editText.getText().toString();
		Properties props = new Properties();
		loadHumanList(props);
		String requestPassword = props.getProperty(User);
		if (Password.equals(requestPassword)) {
			Toast.makeText(this,
					"Успешное подтверждение. Новый пользователь: " + User,	Toast.LENGTH_SHORT).show();
			loadToDB();
		} else {
			Toast.makeText(this, "Неправильный пароль", Toast.LENGTH_SHORT)
					.show();
		}

	}

	/**
	 * @param props в нее будет загружен XML файл
	 * Функция пытается загрузить XML файл со списком пользователей, если она его не 
	 * находит, то создает новый.(Соответсвенно первый запуск)
	 */
	public void loadHumanList(Properties props) {
		File root = new File(Environment.getExternalStorageDirectory(),
				"custodian");		
		File fileForWork = new File(root, "humanDB");

		try {
			FileInputStream xmlStream = new FileInputStream(fileForWork);
			props.loadFromXML(xmlStream);
			xmlStream.close();

		} catch (IOException e) {
			e.printStackTrace();
			generateNewXMLDBOnSD();
		}
	}
	
	/**
	 * Загружает в базу данных нового пользователя.
	 */
	private void loadToDB() {

	}

	/**
	 * Создает новый XML файл в file://sdcard/custodian/humanDB
	 */
	public void generateNewXMLDBOnSD() {
		try {
			File root = new File(Environment.getExternalStorageDirectory(),	"custodian");
			if (!root.exists()) {
				root.mkdirs();
			}
			File newFile = new File(root, "humanDB");
			FileWriter writer = new FileWriter(newFile);
			Properties fastXML = new Properties();
			FileOutputStream xmlStream = new FileOutputStream(newFile);
			fastXML.storeToXML(xmlStream, "");
			writer.flush();
			writer.close();
			Toast.makeText(this, "Cоздана новая База данных пользователей",	Toast.LENGTH_SHORT).show();
			xmlStream.close();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}

	public void newUser_Click(View v) {
		LinearLayout linearlayout1 = (LinearLayout) findViewById(R.id.IdentivicationLayout1);
		LinearLayout linearlayout2 = (LinearLayout) findViewById(R.id.IdentivicationLayout2);
		LinearLayout linearlayout3 = (LinearLayout) findViewById(R.id.IdentivicationLayout3);
		linearlayout1.setVisibility(View.VISIBLE);
		linearlayout2.setVisibility(View.VISIBLE);
		linearlayout3.setVisibility(View.VISIBLE);
	}

	public void newUserAccess_Click(View v)
			throws InvalidPropertiesFormatException, IOException {
		addNewUser();
	}

	/**
	 * @throws IOException
	 * @throws InvalidPropertiesFormatException
	 * Функция добавляет нового пользователя
	 */
	private void addNewUser() throws IOException,
			InvalidPropertiesFormatException {
		LinearLayout linearlayout1 = (LinearLayout) findViewById(R.id.IdentivicationLayout1);
		LinearLayout linearlayout2 = (LinearLayout) findViewById(R.id.IdentivicationLayout2);
		LinearLayout linearlayout3 = (LinearLayout) findViewById(R.id.IdentivicationLayout3);
		linearlayout1.setVisibility(View.INVISIBLE);
		linearlayout2.setVisibility(View.INVISIBLE);
		linearlayout3.setVisibility(View.INVISIBLE);
		EditText newUser = (EditText) findViewById(R.id.IdentificationNewUserName);
		EditText newPassword = (EditText) findViewById(R.id.identificationNewPassword);
		Properties props = new Properties();
		File root = new File(Environment.getExternalStorageDirectory(),	"custodian");
		if (!root.exists()) {
			root.mkdirs();
		}
		File fileForWork = new File(root, "humanDB");
		try {
			FileInputStream xmlInputStream = new FileInputStream(fileForWork);
			props.loadFromXML(xmlInputStream);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		try {
			FileOutputStream xmlStream = new FileOutputStream(fileForWork);

			props.setProperty(newUser.getText().toString(), newPassword.getText().toString());
			props.storeToXML(xmlStream, "");
			Toast.makeText(	this,	"Успешное добавление пользователя "	+ newUser.getText().toString(), Toast.LENGTH_SHORT).show();
			xmlStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			generateNewXMLDBOnSD();
		}
		setListMenu();
	}
	
	public void deleteUser_Click(View v) throws InvalidPropertiesFormatException, IOException{
		deleteUser();
		
	}

	/**
	 * @throws IOException
	 * @throws InvalidPropertiesFormatException
	 * Удаление пользователя, чей ID выбран в списке
	 */
	private void deleteUser() throws IOException,
			InvalidPropertiesFormatException {
		Spinner spinner = (Spinner)findViewById(R.id.identificationSpinner);
		if(spinner.getAdapter().getCount()!=0){
		Properties props = new Properties();
		String User = spinner.getSelectedItem().toString();
		File root = new File(Environment.getExternalStorageDirectory(),	"custodian");
		if (!root.exists()) {
			root.mkdirs();
		}
		File fileForWork = new File(root, "humanDB");
		try {
			FileInputStream xmlInputStream = new FileInputStream(fileForWork);
			props.loadFromXML(xmlInputStream);

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		try {
			FileOutputStream xmlStream = new FileOutputStream(fileForWork);

			props.remove(User);
			props.storeToXML(xmlStream, "");
			Toast.makeText(	this,	"Успешное удаление записи "	+ User, Toast.LENGTH_SHORT).show();
			xmlStream.close();
		} catch (IOException e) {
			e.printStackTrace();
			generateNewXMLDBOnSD();
		}
		setListMenu();
		
	}
		else{
			Toast.makeText(	this,	"Список пользователей пуст", Toast.LENGTH_SHORT).show();
		}
	}

}
